package com.teamone.mobilewatch;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.teamone.mobilewatch.accessor.webservice.PatientWatchDataAccessorImpl;
import com.teamone.mobilewatch.model.Patient;
import com.teamone.mobilewatch.model.Watchlist;

/**
 * Screen to edit Patientwatch by adding/removing patients from the watchlist
 * 
 */
public class EditActivity extends Activity {

	private static final String TAG = "EditActivity";

	private ArrayList<Patient> patients = null;
	private PatientAdapter adapter;
	private Watchlist watchlist;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit);
		watchlist = Watchlist.getInstance();
		watchlist.loadFromPersistence(this); // loads previously saved data

		patients = new ArrayList<Patient>();

		this.adapter = new PatientAdapter(this,
				R.layout.list_item_two_line_checkbox, patients);
		ListView lstPatientsAll = (ListView) findViewById(R.id.lstPatientsAll);
		lstPatientsAll.setAdapter(adapter);
		lstPatientsAll.setItemsCanFocus(false);
		lstPatientsAll.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		// add listener to handle selection
		lstPatientsAll.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long id) {
				Log.d(TAG, "onItemClick arg2=" + position + "id=" + id + "tag="
						+ view.getTag());
				CheckBox chk = (CheckBox) view.findViewById(R.id.chkSelected);

				int patientId = (Integer) view.getTag(); // read id from the tag
				if (!chk.isChecked()) {
					chk.setChecked(true);
					// add to watchlist
					watchlist.add(patientId, null);
				} else {
					chk.setChecked(false);
					// remove from watchlist
					watchlist.remove(patientId);
				}
				adapter.notifyDataSetChanged();
			}
		});

		new LoadPatientsTask().execute();
	}

	@Override
	protected void onStop() {
		super.onStop();
		watchlist.saveToPersistence(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {


		case R.id.details:
			startActivity(new Intent(this, DetailsActivity.class));
			return true;

		case R.id.settings:
			startActivity(new Intent(this, SettingsPreferenceActivity.class));
			return true;

		case R.id.admin:
			startActivity(new Intent(this, AdminActivity.class));
			return true;

		default:
			break;
		}

		return false;
	}


	
	/**
	 * Extension of ArrayAdapter for custom two lines & checkbox ListView
	 * 
	 */
	private class PatientAdapter extends ArrayAdapter<Patient> {

		private ArrayList<Patient> items;

		public PatientAdapter(Context context, int textViewResourceId,
				ArrayList<Patient> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.list_item_two_line_checkbox, null);
			}
			Patient p = items.get(position);

			if (p != null) {
				TextView txt1 = (TextView) v.findViewById(R.id.txtLine1);
				TextView txt2 = (TextView) v.findViewById(R.id.txtLine2);
				CheckBox chk = (CheckBox) v.findViewById(R.id.chkSelected);
				if (txt1 != null) {
					txt1.setText(p.getFirstName() + " " + p.getLastName());
				}
				if (txt2 != null) {
					txt2.setText("Room: " + p.getRoom() + ", "
							+ p.getDepartment());
				}
				if (chk != null) {
					chk.setChecked(watchlist.containsId(p.getPatientId()));
				}
				v.setTag(new Integer(p.getPatientId()));
			}
			return v;
		}
	}

	/**
	 * 
	 * Async task to load Patients and set checked if registered in watchlist
	 * 
	 */
	private class LoadPatientsTask extends AsyncTask<Void, Void, Void> {
		private static final String TAG = "LoadPatientsTask";
		String err = null;
		private ProgressDialog progressDialog = null;

		protected void onPreExecute() {
			if (progressDialog == null) {
				progressDialog = ProgressDialog.show(EditActivity.this,
						"Please wait...", "Retrieving data ...", true);
			}
			Toast.makeText(
					getApplicationContext(),
					"Check patients to add to watchlist or uncheck to remove from the watchlist.",
					Toast.LENGTH_LONG).show();

		}

		// automatically done on worker thread (separate from UI thread)
		protected Void doInBackground(final Void... unused) {
			try {
				Log.d(TAG, "loading patients data...");
				patients = PatientWatchDataAccessorImpl.getInstance()
						.getAllPatients();
			} catch (Exception e) {
				err = e.getMessage();
				Log.d(TAG, err);
			}
			return null;
		}

		// can use UI thread here
		protected void onPostExecute(final Void unused) {
			// update adapter
			if (patients != null && patients.size() > 0) {
				for (int i = 0; i < patients.size(); i++)
					adapter.add(patients.get(i));
			}
			adapter.notifyDataSetChanged();

			// close progress
			if (progressDialog != null) {
				progressDialog.dismiss();
				progressDialog = null;
			}

			// report error if any
			if (err != null) {
				new AlertDialog.Builder(EditActivity.this)
						.setMessage(err)
						.setTitle("Error")
						.setNeutralButton(android.R.string.ok,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
									}
								}).show();

				err = null;
			}

		}

	}

}
